﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace myFirtz.Interface
{
    public static class Helper
    {
        public static Exception LastException;

        public static string SeiteEinlesen(string url, string sid)
        {
            Uri uri = new Uri(url + "?sid=" + sid);
            HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string str = reader.ReadToEnd();
            return str;
        }

        public static string GetMD5Hash(string input)
        {
            MD5 md5Hasher = MD5.Create();
            byte[] data =
            md5Hasher.ComputeHash(Encoding.Unicode.GetBytes(input));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("x2"));
            }
            return sb.ToString();
        }

        public static string GetValue(XDocument doc, string name)
        {
            XElement info = doc.FirstNode as XElement;
            return info.Element(name).Value;
        }

        public static string SendCmd(string Identifier, string cmd, string param, Session session)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://{0}/webservices/homeautoswitch.lua?Identifier={1}&switchcmd={2}&sid={3}", session.Server, Identifier, cmd, session.Sid));

                request.Method = "GET";
                
                
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                return (responseString);
            }
            catch (Exception ex)
            {
                Helper.LastException = ex;
                return (string.Empty);
            }
        }

        public static XDocument GetSwitchList(Session session)
        {
            string uri = string.Format("http://{0}/webservices/homeautoswitch.lua?switchcmd=getSwitchlistinfos&sid={1}", session.Server, session.Sid);
            XDocument doc = XDocument.Load(uri);

            return (doc);
        }               
    }
}
